
import java.io.IOException;
import java.io.PrintWriter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.client.ContinueProtocolHandler;
import org.eclipse.jetty.continuation.Continuation;
import org.eclipse.jetty.continuation.ContinuationListener;
import org.eclipse.jetty.continuation.ContinuationSupport;

import com.google.gson.Gson;

import pojo.Message;
import util.MessageParser;

/**
 * Servlet implementation class MessageController
 */

public class MessageController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private ArrayList<Message> listMessage = new ArrayList<Message>();
	private Gson gson = new Gson();
	private Continuation continuation ;
	private Map<String, Continuation> continuations = new HashMap<String,Continuation>();
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// response.setContentType("application/json; charset=UTF-8");
		

		//MessageParser parser = new MessageParser(request.getPathInfo());
		//Integer fromIndex = parser.getId();
		if(request.getParameter("fromIndex")!=null){
			int fromIndex = Integer.parseInt(request.getParameter("fromIndex"));
			String username = request.getParameter("name");
			poll(request, response, fromIndex, username);
			System.out.println("index "+ fromIndex);
		} else {
			System.out.println("dasdas");
		}
		
		/*if (fromIndex <= listMessage.size()) {
			Continuation continuation = ContinuationSupport.getContinuation(request);
			if (continuation.isInitial()) {
				continuation.setTimeout(5000);
				continuation.suspend();
				
			} else {
				out = response.getWriter();
				out.write("");
				System.out.println("Time out!");
			}
		} else {
			int toIndex = listMessage.size(); 
			List<Message> listToSend = listMessage.subList(fromIndex,toIndex); 
			String jsonObject = gson.toJson(listToSend);
			response.setContentType("application/json; charset=UTF-8"); 
			out= response.getWriter(); 
			out.write(jsonObject);
		}*/
		

		/*
		 * if(fromIndex != null){ if(fromIndex == -1){ // get all message int
		 * fromIndex = listMessage.size()-1; ArrayList<Message> listToSend =
		 * (ArrayList<Message>)listMessage.subList(toIndex,fromIndex); String
		 * jsonObject = gson.toJson(listToSend);
		 * response.setContentType("application/json; charset=UTF-8"); out=
		 * response.getWriter(); out.write(jsonObject);
		 * response.setContentType("text/html"); out= response.getWriter();
		 * out.write(String.valueOf (listMessage.size())); } else{
		 * 
		 * int toIndex = listMessage.size(); List<Message> listToSend =
		 * listMessage.subList(fromIndex,toIndex); String jsonObject =
		 * gson.toJson(listToSend);
		 * response.setContentType("application/json; charset=UTF-8"); out=
		 * response.getWriter(); out.write(jsonObject); } }
		 */
	}
	private synchronized void poll (HttpServletRequest request, HttpServletResponse response, int fromIndex, String username) throws IOException{
		if (fromIndex == listMessage.size()) {
			
			/*if (continuations.get(username) == null) {
				
			} else {*/
			System.out.println(username + " post!!");
				Continuation continuation = ContinuationSupport.getContinuation(request);
				continuations.put(username, continuation);
			//}
			
			if (continuation.isInitial()) {
				continuation.setTimeout(20000);
				continuation.suspend();
				
			} else {
				PrintWriter out;
				out = response.getWriter();
				out.write("");
				System.out.println("Time out");
			}
		/*	if (continuation.isExpired()) {
				PrintWriter out;
				out = response.getWriter();
				out.write("");
				System.out.println("Time out!");
				return;
			}*/
			
			
		} else {
		
			int toIndex = listMessage.size(); 
			List<Message> listToSend = listMessage.subList(fromIndex,toIndex); 
			String jsonObject = gson.toJson(listToSend);
			response.setContentType("application/json; charset=UTF-8"); 
			PrintWriter out;
			out = response.getWriter(); 
			out.write(jsonObject);
		}
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		if (request.getParameter("fromIndex") == null) {
			
			request.setCharacterEncoding("UTF-8");
			Message message = gson.fromJson(request.getReader(), Message.class);
			System.out.println("Message post : " + message.getContent());
			/*if (continuations.get(message.getName()) != null) {
				continuations.get(message.getName()).resume();
				//continuations.put(message.getName(),null); 
			}*/
			for (Continuation con : continuations.values()) {
				con.resume();
			}
			
			listMessage.add(message);
		} else {
			doGet(request, response);
		}
		


	}

}
